app.controller('GoodsListCtrl', ['$scope','$state','$stateParams','$filter','appFactory',function($scope, $state,$stateParams,$filter,appFactory) {
    var Product = AV.Object.extend('Product');
    var Order = AV.Object.extend('Order');
    var CourierCart = AV.Object.extend('CourierCart');
    var RebateFlowM = AV.Object.extend("RebateFlow");
    $scope.user=appFactory.getUserInfo();
    $scope.search={searchInput:""};
    $scope.address={};
    /**
     *主页/搜索
     * @param search 搜索内容
     */
    $scope.initGood=function(search){
        producType=[2,3]
        query=new AV.Query(Product);
        query.equalTo('status',1);
        query.containedIn('productType',producType);
        if($scope.search.searchInput!=""){
            query.contains('name',search);
        }
        query.find().then(function(res){
            $scope.$apply(function(){
                $scope.goodsList=res;
            });
        }).finally(function(){
                $scope.$broadcast('scroll.refreshComplete');
        });
    }

    $scope.initGood("");

    /**
     * 选择规格
     * @param ind
     * @param good
     * @param pec
     */
    $scope.selectSpec=function(ind,good,pec){
        angular.forEach($scope.goodsList,function(data,index,array){
            if($scope.goodsList[index].id==good.id){
                if(good.get('productType')!=3){
                    $scope.goodsList[index].set("minPrice",pec.grprice);
                }
                $scope.goodsList[index].set("minSpec",pec.id);
            }
        })
    }

    /**
     *pre下单函数
     * @param ind 索引值
     * @param good 商品对象
     */
    $scope.createOrder=function(ind,good){
        if(good.get('minSpec')==""){
            alert('请选择规格');
        }else{
            var couriercartQuery=new AV.Query(CourierCart);
            couriercartQuery.equalTo("psid",good.get('minSpec'));
            couriercartQuery.equalTo("pid",good.id);
            couriercartQuery.equalTo("uid",String($scope.user.uid));
            couriercartQuery.equalTo("status",1);
            couriercartQuery.first().then(function(res){
                if(res){
                    alert("加入成功");
                }else{
                    var couriercart = new CourierCart();
                    couriercart.set("psid",good.get('minSpec'));
                    couriercart.set("pid",good.id);
                    couriercart.set("uid",String($scope.user.uid));
                    couriercart.set("status",1);
                    couriercart.set("productType",good.get('productType'));
                    couriercart.set("num",1);
                    couriercart.save().then(function(){
                        alert("加入成功");
                    }).catch(function(){
                        alert("加入失败");
                    })
                }
            })

        }

    }
    $scope.goToCart = function(){
        $state.go('app.marketOrders') ;
    }
}]);

//确认订单
app.controller('MarketOrderCtrl', ['$scope','$state','$stateParams','appFactory','$cordovaBarcodeScanner',function($scope,$state, $stateParams,appFactory,$cordovaBarcodeScanner) {
    var uid = appFactory.getUserInfo().uid;
    var area = appFactory.globalArea();
    $scope.doRefresh = function(){
        $scope.showProList() ;
    }
    //快递员购物车
    var CourierCart = AV.Object.extend('CourierCart');
    var Product = AV.Object.extend('Product');
    var Order = AV.Object.extend('Order');
    $scope.product={allAmount: 0};
    $scope.product={orderAddress:''};
    $scope.showProList=function(){
        $scope.product={allAmount: 0};
        async.auto({
            getCart:function(callback){
                var queryCourierCart = new AV.Query(CourierCart);
                //query.limit(10);
                queryCourierCart.equalTo('uid',uid+"");
                queryCourierCart.equalTo('status',1);
                queryCourierCart.find().then(function(res){
                    console.log(res);
                    callback(null, res);
                });
            },
            getProduct:["getCart",function(callback,results){
                if(results.getCart){
                    var array =new Array();
                    async.eachSeries(results.getCart,function(eachInfo,callback1){
                        //查询出所有商品的信息
                        var queryProduct = new AV.Query(Product);
                        queryProduct.get(eachInfo.get('pid')).then(function(res){
                            //JSON.parse(eachInfo.get('picurlarray'))[0]
                            var picarray = res.get('picurlarray') ;
                            var picture = '';
                            if(picarray!=''){
                                var pictures = JSON.parse(picarray);
                                picture = pictures[0] ;
                            }else{
                                picture = '';
                            }
                            //alert(eachInfo.get('productType'));
                            var price = 0;
                            if(eachInfo.get('productType')===3){
                                price = res.get('minPrice') ;
                            }else{
                                price = res.get('spec')[eachInfo.get('psid')].grprice ;
                            }
                            var specName = "" ;
                            if(eachInfo.get('productType')===3){
                                specName = "" ;
                            }else{
                                specName = res.get('spec')[eachInfo.get('psid')].name ;
                            }
                            array.push(
                                {
                                    "cartId":eachInfo.id,
                                    'pid':res.id,
                                    'name':res.get('name'),
                                    "pictrue":picture,
                                    "psid":eachInfo.get('psid'),
                                    "spec":res.get('spec')[eachInfo.get('psid')],
                                    "specName":specName,
                                    "type":eachInfo.get('productType'),
                                    "minPrice" :res.get('minPrice'),
                                    "price":price,
                                    "num":eachInfo.get('num'),
                                    "inventory":res.get('spec')[eachInfo.get('psid')].inventory
                                }
                            );
                            callback1(null, array);
                        }).catch(function(err){
                            console.log(err);
                        });
                    },function(){
                        callback(null, array);
                    });
                }else{
                    callback(null, []);
                }
            }],
            /*finalFun:["getProduct",function(callback,results){
                console.log('//////////////')
                alert(results.getProduct);
                callback(null, results.getProduct);
            }],*/
        },function(err,results){
            if(err){
                console.log(err);

                $scope.$broadcast('scroll.refreshComplete');
            }else{
                $scope.good={number:1};
                $scope.product={allAmount: 0};
                for(var x in results.getProduct){
                    $scope.product.allAmount = $scope.product.allAmount+parseInt(results.getProduct[x].price) * parseInt(results.getProduct[x].num);
                }
                //console.log("总价："+$scope.product.allAmount);
                $scope.cartlist =results.getProduct;
                $scope.$broadcast('scroll.refreshComplete');
            }
        });
    };
    $scope.showProList();

    $scope.minus=function(index,good){
        if(good.inventory < 1){
            good.num=0;
        }else{
            var mini = 1;
            var old = good.num ;
            good.num = (parseInt(good.num) > mini)?(parseInt(good.num)-1):mini;
            var newM = good.num ;
            $scope.product.allAmount = $scope.product.allAmount-parseInt(good.price)*(old-newM);
            if(parseInt(good.num) > 1){

            }
        }

    }
    /**
     *  增加购买数量
     */
    $scope.plus = function(index,good){
        if(good.inventory < 1){
            good.num=0;
        }else{
            var inventory  = good.inventory;
            var size = parseInt(good.num);
            var maxSize = inventory;
            var old = good.num ;
            good.num = (parseInt(size) < maxSize)?(parseInt(size)+1):maxSize;
            var newM = good.num ;
            $scope.product.allAmount = $scope.product.allAmount-parseInt(good.price)*(old-newM);
        }
    };
    //删除某一个商品
    $scope.trashOne=function(index,good){
        var couriercartQuery = new AV.Query(CourierCart);
        couriercartQuery.get(good.cartId).then(function (res) {
            res.destroy().then(function(){
                //alert('删除商品成功');
                //window.location.reload();
                $scope.showProList();
            }).catch(function(err){
                //alert('删除商品失败1');
                //window.location.reload();
                $scope.showProList();
            });
        }).catch(function(err){
            //alert('删除商品失败2');
            //window.location.reload();
            $scope.showProList();
        });
    };
    //清空购物车
    $scope.trashAll=function(){

        console.log(uid);
        var couriercartQuery = new AV.Query(CourierCart);
        couriercartQuery.equalTo('uid',uid+'');
        couriercartQuery.destroyAll().then(function () {
            //alert('清空购物车成功');
            //window.location.reload();
            $scope.showProList();
        }).catch(function(err){
            //alert('清空购物车失败');
            //window.location.reload();
            $scope.showProList();
        });
    };

    $scope.amountNow = function(){

        var allAmount = $scope.product.allAmount;      //订单金额
        var Address = $scope.product.orderAddress;     //用户地址
        var username = $scope.product.name;            //客户姓名
        var phone = $scope.product.phone;              //联系电话
        var areaId = $scope.product.areaid;            //区域
        var shopId = $scope.product.shopid;            //店铺

        if(!Address || !username || !phone){
            alert("请选择收货信息!");
            return;
        }

        var aId = "";
        var status = "";
        var sId = "";
        if(areaId){
            aId = areaId;
            sId = shopId;
            status = 2500;
        }else{
            aId = "";
            sId = "";
            status = 2000;
        }

        $scope.address={address:Address,phone:phone,name:username};

        var storage = window.localStorage;
        var uid = storage.getItem("uid");              //快递员用户编号
        //var sellerNo = storage.getItem("jobnumber");              //快递员用户编号
        var sellerNo = appFactory.getUserInfo().user.jobnumber;

        var total = parseFloat(allAmount);

        var str = '货到付款';

        var goods1 = new Array();
        var goods2 = new Array();
        var timestamp = new Date().getTime();
        var orderid = 'Y'+timestamp;

        var je1 = 0;
        var je2 = 0;
        var spec;
        var psRebate1 = 1;           //配送提成
        var psRebate2 = 1;           //配送提成
        var yxRebate1 = 0;           //营销提成
        var yxRebate2 = 0;           //营销提成

        var jsontext = "";

        async.waterfall([
            function(callback){
                var CourierCart = AV.Object.extend('CourierCart');
                var queryCourierCart = new AV.Query(CourierCart);
                queryCourierCart.equalTo('uid',uid);
                queryCourierCart.find().then(function(cartList){
                    callback(null, cartList);
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
            },
            function(cartList,callback){
                if(!cartList || cartList.length<1){
                    //购物车内没有数据
                    callback({code:9999,reason:err});
                }

                async.eachSeries(cartList,function(each,callback1){
                    var ProductM = AV.Object.extend('Product');
                    var queryPro = new AV.Query(ProductM);
                    queryPro.get(each.get('pid')).then(function(product){
                        each.set('product',product);
                        callback1(null, cartList);
                    }).catch(function(err){
                        callback({code:9999,reason:err});
                    });
                },function(){
                    callback(null,cartList);
                });
            },
            function(cartList,callback){
                    var pid;
                    var psid;
                    var specArray;
                    var imgArray;
                    var pro_num = 0;
                    var productType = 2;

                    if (cartList.length > 0) {
                        for (x in cartList) {
                            pid = cartList[x].get('pid');
                            psid = cartList[x].get('psid');
                            productType = cartList[x].get('productType');
                            pro_num = cartList[x].get('num');

                            if(parseInt(pro_num) <= 0){
                                return callback({code:506});   //code:506 购买商品数量为0
                            }

                            specArray = cartList[x].get('product').get('spec'); //读取商品规格数组
                            imgArray = JSON.parse(cartList[x].get('product').get('picurlarray'));//读取商品图片数组


                            for(var i in specArray){
                                specArray[i]['size'] = parseInt(pro_num);
                                specArray[i]['sid'] = psid;
                            }

                            console.log('============');
                            console.log(specArray);

                            if(productType==2){

                                //营销商品
                                goods1.push(
                                    {
                                        mid:        pid,
                                        pname:      cartList[x].get('product').get('name'),
                                        sid:        psid,
                                        sname:      specArray[psid].name,
                                        price:      parseInt(specArray[psid].grprice),
                                        size:       parseInt(pro_num),
                                        img:        imgArray[0]
                                    }
                                );

                                je1 = je1 + (parseInt(specArray[psid].grprice) * parseInt(cartList[x].get('num')));

                                yxRebate1 = yxRebate1+(parseInt(specArray[psid].grprice) * parseInt(cartList[x].get('num')) * parseInt((specArray[psid].yxRate||0)) / 100);

                            }else{
                                //套餐商品(包月商品)
                                goods2.push(
                                    {
                                        mid:        pid,
                                        mname:      cartList[x].get('product').get('name'),
                                        pid:        specArray[psid].pid,
                                        pname:      specArray[psid].pname,
                                        sid:        specArray[psid].id,
                                        sname:      specArray[psid].name,
                                        price:      parseInt(specArray[psid].grprice),
                                        size:       parseInt(pro_num),
                                        spec:       specArray,
                                        img:        imgArray[0]
                                    }
                                );

                                je2 = je2 + (parseInt(specArray[psid].grprice) * parseInt(cartList[x].get('num')));

                                yxRebate2 = yxRebate2+(parseInt(specArray[psid].grprice) * parseInt(cartList[x].get('num')) * parseInt((specArray[psid].yxRate||0)) / 100);

                            }
                        }
                        callback(null,cartList);
                    }else{
                        callback({code:505});   //code:505 购物车内已无商品，请刷新页面
                    }
            },
            //生成营销普通订单
            function(cartList,callback){
                if(goods1.length == 0){
                    callback(null,cartList);
                }else{
                    je1 = parseFloat(parseFloat(je1).toFixed(2));
                    var order = new Order();

                    order.set('goods',goods1);
                    order.set('psRebate',psRebate1);
                    order.set('yxRebate',yxRebate1);
                    order.set('finalAmount',je1);
                    order.set('total',je1);
                    order.set('type',8);
                    order.set('description',str+':'+je1+' 元');

                    jsontext = '[{"way":"'+str+'","pay":'+je1+'}]';
                    order.set('orderid',orderid);
                    order.set('payway',str);
                    order.set('uid',uid);
                    order.set('messionedUser',uid);
                    order.set('refereeUser',uid);
                    order.set('sellerNo',sellerNo);
                    order.set('status',status);
                    order.set('areaId',aId);
                    order.set('shopId',sId);
                    var ss;
                    var s = timestamp+'';
                    ss = s.substring(0,10);

                    order.set('bookdate',ss);
                    order.set('canceltime',timestamp+(2*60*60));
                    order.set('address',$scope.address);
                    order.set('details',JSON.parse(jsontext));
                    order.set('syncStatus',1);
                    order.set('paytime',timestamp);
                    order.set('location',new AV.GeoPoint({latitude: 39.9, longitude: 116.4}));

                    order.save().then(function(result){
                        //保存成功
                        callback(null,cartList);
                    }).catch(function(err){
                        //保存失败
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //生成营销包月订单
            function(cartList,callback){
                str = '已付款';
                console.log('============4');
                if(goods2.length == 0){
                    callback(null,cartList);
                    return;
                }
                async.eachSeries(goods2,function(eachInfo1,callback1){

                    timestamp = new Date().getTime();
                    orderid = 'Y'+timestamp;
                    var idx = 1;

                    var specs = eachInfo1.spec;

                    var mname = eachInfo1.mname;

                    async.eachSeries(specs,function(eachInfo2,callback2){
                        var orderM = AV.Object.extend("Order");
                        var order = new orderM();

                        var goodsArr = [];
                        goodsArr.push(eachInfo2);
                        order.set('goods',goodsArr);
                        order.set('psRebate',psRebate2);
                        order.set('yxRebate',yxRebate2);
                        order.set('finalAmount',0);
                        order.set('total',0);
                        order.set('type',7);
                        order.set('description',str+':0 元');

                        jsontext = '[{"way":"'+str+'","pay":0}]';
                        order.set('orderid',orderid+'-'+idx);
                        order.set('payway',str);
                        order.set('uid',uid);
                        order.set('messionedUser',uid);
                        order.set('refereeUser',uid);
                        order.set('sellerNo',sellerNo);
                        order.set('status',status);
                        order.set('areaId',aId);
                        order.set('shopId',sId);
                        order.set('bytcname',mname);

                        var ss = '';
                        //var s = timestamp+'';
                        //ss = s.substring(0,10);

                        order.set('bookdate',ss);
                        order.set('canceltime',timestamp+(2*60*60));
                        order.set('address',$scope.address);
                        order.set('details',JSON.parse(jsontext));
                        order.set('syncStatus',1);
                        order.set('paytime',timestamp);
                        order.set('location',new AV.GeoPoint({latitude: 39.9, longitude: 116.4}));

                        order.save().then(function(result){
                            //保存成功
                            callback2(null,cartList);
                        }).catch(function(err){
                            //保存失败
                            callback2({code:9999,reason:err});   //code:9999 系统错误
                        });
                        idx = idx + 1;

                    },function(err){
                        if(err){
                            callback1(err);
                        }else{
                            callback1(null,cartList);
                        }
                    });
                },function(err,results) {
                    if(err) {
                        callback(err);
                    }else{
                        callback(null,cartList);
                    }
                });
            },
            //删除购物车商品
            function(cartList,callback){
                console.log(5);

                if(!cartList || cartList.length<1){
                    //购物车内没有数据
                    callback(null);
                }

                cartList.forEach(function (val) {
                    val.destroy().then(function(){
                        callback(null);
                    }).catch(function(err){
                        callback({code:9999,reason:err});       //code:9999 系统错误
                    });
                });
            },

            //生成流水信息
            function(callback){

                var FlowM = AV.Object.extend("OrderFlow");
                var flow = new FlowM();
                flow.set('orderid',orderid);
                flow.set('amount',total);
                flow.set('paytime',new Date().getTime());
                flow.set('userid',uid);
                flow.set('content','使用'+str+total+'元.');
                flow.save().then(function(result){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });
            }
        ],function(err){
            if(err){
                alert("下单失败!");
                console.log(err);
                $state.go('app.marketOrders');
                //res.json(err);
            }else{
                alert("下单成功!");
                $state.go('app.orders');
            }
            //res.json(result);
        });
    }

    $scope.barscanReceive = function(){
        $cordovaBarcodeScanner
            .scan()
            .then(function(barcodeData) {
                var cancelled = barcodeData.cancelled;
                var result = JSON.parse(barcodeData.text);
                if(!cancelled){
                    var oid = result.OID;
                    var aid = result.AID ;
                    var shopid = result.WID ;
                    if(oid){
                        //获取到orderid，根据orderid获取address信息
                        var queryOrder = new AV.Query(Order);
                        queryOrder.equalTo('orderid',oid);
                        queryOrder.first().then(function(res){
                            if(res){
                                var address = res.get('address');
                                alert("获取地址信息:"+address.address);
                                $scope.$apply(function(){
                                    $scope.product.orderAddress = address.address;
                                    $scope.product.name = address.name;
                                    $scope.product.phone = address.phone;
                                    $scope.product.address = address ;
                                    $scope.product.areaid = aid ;
                                    $scope.product.shopid = shopid ;
                                });
                                //alert('地址返写成功');

                            }else{
                                alert('没有获取到地址信息');
                                /*$scope.product.orderAddress = "";
                                 $scope.product.orderAddress ="";
                                 $scope.product.name = "";
                                 $scope.product.phone = "";
                                 $scope.product.address = "" ;*/
                            }
                        }).catch(function(){
                            alert("扫码失败，请手动输入");
                        });
                    }else{
                        alert('没有获取到oid');
                    }
                }
            }, function(error) {
                // An error occurred
                alert("扫码失败，请手动输入");
            });
    }
}]);

